package com.woniuxy.ams.service.impl;

import com.woniuxy.ams.dao.RoleDao;
import com.woniuxy.ams.dao.UserDao;
import com.woniuxy.ams.dao.UserRoleDao;
import com.woniuxy.ams.entity.Role;
import com.woniuxy.ams.entity.User;
import com.woniuxy.ams.exception.RoleNotExistException;
import com.woniuxy.ams.exception.UserNotExistException;
import com.woniuxy.ams.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fyx
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;
    @Resource
    private UserDao userDao;
    @Resource
    private UserRoleDao userRoleDao;

    @Override
    public List<Role> findAllRolesAndSearch(Role role) {
        return roleDao.findAllRolesAndSearch(role);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean setRoleByUser(User user, List<Role> roles) {
        User userInDb = userDao.findOneByName(user.getName());
        if (userInDb == null) {
            throw new UserNotExistException(user.getName());
        }
        List<Role> rolesInDb = roleDao.findRolesByIds(roles.parallelStream().map(Role::getId).collect(Collectors.toList()));
        if (rolesInDb.size() == 0) {
            throw new RoleNotExistException();
        }
        userRoleDao.delete(userInDb.getId());
        userRoleDao.addRole(userInDb.getId(), rolesInDb.parallelStream().map(Role::getId).collect(Collectors.toList()));
        return true;
    }

    @Override
    public List<Integer> getRoles(int uid) {
        return roleDao.findRolesByUid(uid);
    }
}
